package com.veo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.veo.entity.Admin;
import com.veo.entity.User;
import com.veo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/toAdmin")
    public String toAdmin(){
        return "admin/adminManage";
    }


    @GetMapping("/getAllAdmin")
    @ResponseBody
    public List<Admin> getAllAdmin(){
        return adminService.list();
    }

    /**
     * 检查管理员名称是否重复
     * @param name
     * @return
     */
    @RequestMapping("/searchAdminName")
    @ResponseBody
    public Map<String,Object> searchUserName(String name){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name);
        Admin admin = adminService.getOne(wrapper);
        if (admin != null){
            map.put("msg","error");
            return map;
        }
        map.put("msg","ok");
        return map;
    }

    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @ResponseBody
    @RequestMapping("/addAdmin")
    public Map<String, Object>  addAdmin(Admin admin){
        boolean flag = adminService.save(admin);
        return returnMsg(flag);
    }

    /**
     * 修改管理员信息
     * @param admin
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateAdmin")
    public Map<String, Object>  updateAdmin(Admin admin, HttpSession session){
        boolean flag = adminService.updateById(admin);
        session.setAttribute("admin",adminService.getById(admin));
        return returnMsg(flag);
    }

    /**
     * 删除管理员信息
     * @param id
     * @return
     */
    @RequestMapping("/deleteAdminById")
    @ResponseBody
    public Map<String, Object>  deleteAdminById(Integer id){
        boolean flag = adminService.removeById(id);
        return returnMsg(flag);
    }

    private Map<String, Object> returnMsg(boolean flag){
        Map<String,Object> map = new HashMap<>();
        if (flag){
            map.put("msg","ok");
            return map;
        }
        map.put("error","no");
        return map;
    }
}
